package com.chaopei.day35.tools;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chaopei.day35.entity.Cool;

import java.util.List;
import java.util.Map;

/**
 * @Author yws
 * @Date 2022/4/20 14:21
 * json字符串与java对象的解析
 */
public class MyTools {
    //1.1java对象转为json字符串
    public static String javaToJson(Object obj){
        //普通的java自定义对象
        Cool cool = new Cool(101,"tom");
        //解析为JSON字符串
        String s = JSONObject.toJSONString(cool);
        System.out.println(s);
        return s;
    }

    //2.将json字符串解析并转换为java对象
    //2.1准成Cool
    public static Object jsonToJava1(){
        String json = "{'add':'郑州市五四大街','arr':[{'id':8,'name':'tom'},{'id':9,'name':'lisa'}]" +
                ",'cool':{'id':10,'name':'mary'}}";
        JSONObject o =JSONObject.parseObject(json);
        Object obj = o.get("add");
        System.out.println("obj:"+obj);
        System.out.println(o.getString("add"));
        System.out.println("--解析出cool对象--");
        JSONObject cool = o.getJSONObject("cool");
        System.out.println(cool.toJavaObject(Cool.class));
        return null;
    }
    //2.2转成List<Cool>
    public static Object jsonToJava2(){
        String str = "{'add':'郑州市五四大街','arr':[{'id':8,'name':'tom'},{'id':9,'name':'lisa'}]" +
                ",'cool':{'id':10,'name':'mary'}}";
        JSONObject obj = JSONObject.parseObject(str);
        JSONArray arr = obj.getJSONArray("arr");
        List<Cool> list =arr.toJavaList(Cool.class);
        list.forEach(System.out::println);
        System.out.println(list.get(0).getName());
        Object[] object = list.toArray();
        System.out.println(object);
    return null;
    }
    //2.2转成Map
    public static Object jsonToJava3(){
        String str = "{'1':{'id':20,'name':'tina'},'2':{'id':21,'name':'mick'}}";
        JSONObject object = JSONObject.parseObject(str);
        Map map = JSONObject.toJavaObject(object,Map.class);
        System.out.println(map.get("1"));
        return null;
    }

}
